package itstudio.instructor.fragment;

import java.util.ArrayList;
import java.util.List;
import org.apache.http.Header;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.nhaarman.listviewanimations.swinginadapters.AnimationAdapter;
import com.nhaarman.listviewanimations.swinginadapters.prepared.SwingBottomInAnimationAdapter;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import itstudio.app.wq.R;
import itstudio.instructor.adapter.UserListAdapter;
import itstudio.instructor.config.Config;
import itstudio.instructor.config.ImageOptionsUtil;
import itstudio.instructor.entity.User;
import itstudio.instructor.http.TwitterRestClient;
import itstudio.instructor.ui.UserDetailActivity;
import itstudio.instructor.util.LoginUtil;
import itstudio.instructor.xlistview.XListView;
import itstudio.instructor.xlistview.XListView.IXListViewListener;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

/**
* @Description 辅导员 Fragment

* @author MR.Wang

* @date 2014-7-5 上午1:13:26 

* @version V1.0
*/

public class FragmentTeacher extends Fragment  implements IXListViewListener{

	//view
	private View rootView;
	private XListView xListView;
    private LinearLayout loadLayout;
    private LinearLayout loadFaillayout;
    private Button bn_refresh;
	private ImageView ivDeleteText;
	private EditText etSearch;
	private Button btnSearch;
	//config
	protected ImageLoader imageLoader = ImageLoader.getInstance();
	DisplayImageOptions options;
	private UserListAdapter adapter;
	//data
	private List<User> userList = new ArrayList<User>();
	private int page=0;
	private String searchName;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		options = ImageOptionsUtil.headImageOptions();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		rootView = inflater.inflate(R.layout.fragment_instructor,
				container, false);
		Handler handler = new Handler();
		handler.postDelayed(run,400);
		return rootView;
	}

	
	Runnable run = new  Runnable(){

		@Override
		public void run() {
			// TODO Auto-generated method stub
			initView(rootView);
		}};
	/**
	 * 初始化布局文件中的控件
	 */
	private void initView(View view) {


		// initView
		loadLayout = (LinearLayout) view.findViewById(R.id.view_loading);
		loadFaillayout = (LinearLayout) view.findViewById(R.id.view_load_fail);
		bn_refresh = (Button) view.findViewById(R.id.bn_refresh);
	    bn_refresh.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				LoginUtil.Login(getActivity());
				loadUser(1,true);;
			}
		});
	    
	    adapter = new UserListAdapter(getActivity(), userList,
	 				options);
		AnimationAdapter animAdapter = new SwingBottomInAnimationAdapter(
				adapter);
		
		xListView = (XListView) view.findViewById(R.id.Fragment_instructor_listview);
        ivDeleteText = (ImageView)  view.findViewById(R.id.ivDeleteText);
        etSearch = (EditText)  view.findViewById(R.id.etSearch);
        etSearch.setHint(R.string.instructor);
        btnSearch = (Button)  view.findViewById(R.id.btnSearch);
		xListView.setPullLoadEnable(true);
		xListView.setPullRefreshEnable(false);// 取消下拉刷新
		
		animAdapter.setAbsListView(xListView);
		animAdapter.setInitialDelayMillis(100);
		xListView.setXListViewListener(this);
		xListView.setAdapter(animAdapter);

		xListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int position,
					long arg3) {
				if(position==0){
					return;//0 是header
				}
				TextView instructor_name=(TextView) arg1.findViewById(R.id.instructor_name);
				instructor_name.setTextColor(getResources().getColor(R.color.light_black));
				Intent intent = new Intent();
				intent.setClass(getActivity(), UserDetailActivity.class);
				User user = (User) adapter.getItem(position-1); // -1
				intent.putExtra("user", user);
				startActivity(intent);
				
				/*Intent intent = new Intent();
				intent.setClass(getActivity(), SearchActivity.class);
				startActivity(intent);*/

			}
		});

        
		ivDeleteText.setOnClickListener(onclick);
		btnSearch.setOnClickListener(onclick);
		searchName = etSearch.getText().toString();
		
        
        etSearch.addTextChangedListener(new TextWatcher() {
			
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				// TODO Auto-generated method stub
				
			}
			
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub
				
			}
			
			public void afterTextChanged(Editable s) {
				if (s.length() == 0) {
					ivDeleteText.setVisibility(View.GONE);
				} else {
					ivDeleteText.setVisibility(View.VISIBLE);
				}
			}
		});
		
		loadUser(1,true);
	}
	OnClickListener onclick = new OnClickListener() {

		@Override
		public void onClick(View view) {
			// TODO Auto-generated method stub
			switch (view.getId()) {
			case R.id.ivDeleteText:
				etSearch.setText("");
				break;
				
			case R.id.btnSearch:
				if(!searchName.equals(etSearch.getText().toString())){
					searchName =  etSearch.getText().toString();
					loadLayout.setVisibility(View.VISIBLE);
					adapter.clear();
					page=0;
					searchName= etSearch.getText().toString();
					loadSeek(1,true);
					InputMethodManager imm = (InputMethodManager)getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
					imm.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(),InputMethodManager.HIDE_NOT_ALWAYS);
				}
				break;

			default:
				break;
			}
		}
		
	};
	//加载辅导员
	private void loadUser(int page_num,final boolean refesh){
		RequestParams params = new RequestParams();
		params.put("page", page_num);
		TwitterRestClient.post(Config.AC_USER_TEACHER, params, new AsyncHttpResponseHandler(){
			
			@Override
			public void onStart() {
				super.onStart();

			}
			@Override
			public void onFailure(int arg0, Header[] arg1, byte[] arg2,
					Throwable arg3) {
				// TODO Auto-generated method stub
				onLoad();
				loadLayout.setVisibility(View.GONE);
				loadFaillayout.setVisibility(View.GONE);
				if(page==0){
					loadFaillayout.setVisibility(View.VISIBLE);
				}
			}

			@Override
			public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
				//加载成功
				onLoad();
				loadLayout.setVisibility(View.GONE);
				loadFaillayout.setVisibility(View.GONE);
				Gson gson = new GsonBuilder()  
				  .setDateFormat("yyyy-MM-dd HH:mm:ss")  
				  .create();
					
				userList  = gson.fromJson( new String(arg2), new TypeToken<List<User>>(){}.getType());
				page = adapter.appendData(userList,refesh);
				
				if(userList!=null  && userList.size()==10){
					xListView.setPullLoadEnable(true);
				}
				else{
					xListView.setPullLoadEnable(false);
				}
				
			}});
	}
	//加载辅导员
	private void loadSeek(int page_num,final boolean refesh){
		RequestParams params = new RequestParams();
		params.put("page", page_num);
		params.put("user.name", searchName);
		TwitterRestClient.post(Config.AC_USER_SEEK_TEACHER, params, new AsyncHttpResponseHandler(){
			
			@Override
			public void onStart() {
				super.onStart();
				
			}
			@Override
			public void onFailure(int arg0, Header[] arg1, byte[] arg2,
					Throwable arg3) {
				// TODO Auto-generated method stub
				onLoad();
				loadLayout.setVisibility(View.GONE);
				loadFaillayout.setVisibility(View.GONE);
				if(page==0){
					loadFaillayout.setVisibility(View.VISIBLE);
				}
			}
			
			@Override
			public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
				//加载成功
				onLoad();
				loadLayout.setVisibility(View.GONE);
				loadFaillayout.setVisibility(View.GONE);
				Gson gson = new GsonBuilder()  
				.setDateFormat("yyyy-MM-dd HH:mm:ss")  
				.create();
				
				userList  = gson.fromJson( new String(arg2), new TypeToken<List<User>>(){}.getType());
				page = adapter.appendData(userList,refesh);
				
				if(userList!=null  && userList.size()==10){
					xListView.setPullLoadEnable(true);
				}
				else{
					xListView.setPullLoadEnable(false);
				}
				
			}});
	}
	// 设置下拉刷新时间
	@Override
	public void onRefresh() {
		// TODO Auto-generated method stub
		//loadUser();
	}

	// 设置loadmore刷新时间
	@Override
	public void onLoadMore() {
		// TODO Auto-generated method stub
		if(TextUtils.isEmpty(searchName)){
			
			loadUser(page+1,false);
		}
		else{
			loadSeek(page+1, false);
		}

	}

	private void onLoad() {
		xListView.stopRefresh();
		xListView.stopLoadMore();
	}

}
